import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;


public class Music extends Thread {
    private Clip clip;
    private String soundFile = "picture/1234.wav";
    private boolean isPaused = false;

    @Override
    public void run() {
        try {
            // 打开音频输入流
            File audioFile = new File(soundFile);
            AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);

            // 获取音频格式并创建Clip对象
            AudioFormat format = audioStream.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);
            clip = (Clip) AudioSystem.getLine(info);
            clip.open(audioStream);

            // 如果之前处于暂停状态，则从中断点继续播放
            if (isPaused) {
                clip.start();
                isPaused = false;
            } else {
                // 否则从头开始播放
                clip.start();
                clip.loop(Clip.LOOP_CONTINUOUSLY); // 如果需要循环播放，则取消注释这行代码
            }
        } catch (LineUnavailableException | UnsupportedAudioFileException | IOException e) {
            e.printStackTrace();
        }
    }
//暂停
    public void pauseSound() {
        if (clip != null && clip.isRunning()) {
            clip.stop();
            clip.setMicrosecondPosition(clip.getMicrosecondPosition()); // 保存当前位置
            isPaused = true;
        }
    }
//开始
    public void resumeSound() {
        if (clip != null && isPaused) {
            clip.start();
            isPaused = false;
        }
    }
}

